package com.yootk.web.config;

import com.yootk.context.config.SpringApplicationConfig;
import com.yootk.context.config.SpringWebConfig;
import com.yootk.filter.YootkMessageFilter;
import com.yootk.servlet.YootkDispatchServlet;
import jakarta.servlet.*;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.FrameworkServlet;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import java.util.EnumSet;

public class StartWebApplication  extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[]{SpringApplicationConfig.class};
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[]{SpringWebConfig.class};
    }

    @Override
    protected String[] getServletMappings() {
        return new String[]{"/"};
    }

    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter filter = new CharacterEncodingFilter() ;
        filter.setEncoding("UTF-8");
        filter.setForceEncoding(true);
        YootkMessageFilter messageFilter = new YootkMessageFilter() ;
        return new Filter[]{filter,messageFilter};
    }

    @Override
    protected FrameworkServlet createDispatcherServlet(WebApplicationContext servletAppContext) {
        return new YootkDispatchServlet(servletAppContext) ;
    }

    @Override
    protected void customizeRegistration(ServletRegistration.Dynamic registration) {
        long maxFileSize = 2097152 ;
        long maxRequestSize = 5242880 ;
        int fileSizeThreshold = 0 ;
        String tempDir = System.getProperty("java.io.tmpdir");
        MultipartConfigElement element = new MultipartConfigElement(tempDir,maxFileSize,maxRequestSize,fileSizeThreshold) ;
        registration.setMultipartConfig(element);
    }
}
